import 'dart:collection';

import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/purchase_supplier_evaluation_odoo_api.dart';

import 'package:flutter_admin/models/odoo/purchase_supplier_evaluation.dart';

import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';

import 'package:flutter_admin/pages/common/years_date.dart';
import 'package:flutter_admin/utils/eventbus.dart';

import '../../../../generated/l10n.dart';

class Evaluate extends StatefulWidget {
  Evaluate(
      {Key? key,required this.purchaseSupplierEvaluation,required this.project,this.isView = false}):super(key: key);
  final PurchaseSupplierEvaluation purchaseSupplierEvaluation;
  final Map project;
  final bool isView;
  // final List list;
  @override
  _EvaluateState createState() => _EvaluateState();
}

class _EvaluateState extends State<Evaluate> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  List<SelectOptionVO> locationIdList = [];
  bool isAdd = true;
  Map project = {};
  List purchaselist = [];
  List<SelectOptionVO> userIdLIst = [];
  late PurchaseSupplierEvaluation purchaseSupplierEvaluation;
  String evaluationOpinions = "";
  @override
  void initState() {
    super.initState();
    project = widget.project;
    purchaseSupplierEvaluation = widget.purchaseSupplierEvaluation;
    _loadSelectVO();
  }

  _loadSelectVO() async {
    ResponseBodyApi responseBodyApi =
    await PurchaseSupplierEvaluationOdooApi.findAll(data: {
      "domainList": [
        ["evaluation_id", '=', int.parse(purchaseSupplierEvaluation.id!)],
        [
          'template_id',
          '=',
          int.parse(purchaseSupplierEvaluation.templateId!)
        ],
        [
          "project_id",
          "=",
          project["id"]
        ]
      ]
    });
    if (responseBodyApi.success!) {
      if(responseBodyApi.data.length == 0){
        ResponseBodyApi responseBodyApi2 = await DynamicDataApi.getModels(
          model: "purchase.evaluation.item",
          key: "project_id",
          val: project['id'],
        );
        if(responseBodyApi2.success!){
          responseBodyApi.data.forEach((element) {
            element["actual_score"] = 0;
          });
          isAdd = true;
          purchaselist = responseBodyApi2.data;
        }
      } else {
        isAdd = false;
        purchaselist = responseBodyApi.data;
      }
    }
    evaluationOpinions = purchaselist.length != 0? purchaselist[0]["evaluation_opinions"]!= null && purchaselist[0]["evaluation_opinions"] != false ?purchaselist[0]["evaluation_opinions"] :"": "";
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var rows = purchaselist.map((purchase) {
      var result = DataRow(cells: [
        DataCell(Text(purchase['assessment_content'] != false
            ? purchase['assessment_content']
            : "")),
        DataCell(Text(purchase['evaluation_criteria'] != false
            ? purchase['evaluation_criteria']
            : "")),
        DataCell(!widget.isView?CryInput(
                width: 500,
                padding: 5,
                enable: !widget.isView,
                value: purchase['actual_details'] != false
                    ? purchase['actual_details']
                    : "",
                onSaved: (v) {
                  purchase['actual_details'] = v;
                },
              ):Text(purchase['actual_details']!=null?purchase['actual_details'].toString():"")
            ),
        DataCell(Text(purchase['weight_score'] != false
            ? purchase['weight_score'].toString()
            : "")),
        DataCell(!widget.isView?CryInputNum(
                width: 150,
                padding: 5,
                value: purchase['actual_score'] != false
                    ? purchase['actual_score']
                    : 0,
                onSaved: (v) {
                  purchase['actual_score'] = v;
                },
                validator: (v) {
                  if(v!.isEmpty){
                    return "请输入得分";
                  }
                  // if(num.parse(v) == 0){
                  //   return "得分不可以为0";
                  // }
                  // if(num.parse(v) <= 0){
                  //   return "得分不可以小于0";
                  // }
                  if(num.parse(v)>purchase['weight_score']){
                    return "得分应小于权重分数";
                  }
                  return null;
                },
              ):Text(purchase['actual_score']!=null?purchase['actual_score'].toString():""),
            ),
      ]);
      return result;
    }).toList();
    var table = DataTable(
      columns: [
        DataColumn(
          label: Text('考核内容'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('评估等级标准'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('实际详情'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('权重/100'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
        DataColumn(
          label: Text('得分'),
          //onSort: (int columnIndex, bool ascending) => _sort('create_date'),
        ),
      ],
      rows: rows,
    );
    var form = Form(
      key: formKey,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Row(
            children: <Widget>[
              CryInput(
                label: '考评项目',
                width: 320,
                value: project["evaluation_project"],
                enable: false,
                validator: (v) {
                  return v!.isEmpty ? S.of(context).required : null;
                },
              ),
              CryInput(
                label: '考评意见',
                width: 500,
                enable: !widget.isView,
                value: evaluationOpinions,
                onSaved: (v){
                  evaluationOpinions = v!;
                },
              ),
            ],
          ),
          Row(
            children: [
              table
            ],
          )
        ],
      )
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
            label: S.of(context).save,
            onPressed: () {
              FormState form = formKey.currentState!;
              if (!form.validate()) {
                return;
              }
              form.save();
              List list = [];
              if(isAdd){
                purchaselist.forEach((element) {
                  Map map = new HashMap();
                  map = {
                    'evaluation_id': int.parse(widget.purchaseSupplierEvaluation.id!),
                    'template_id': int.parse(widget.purchaseSupplierEvaluation.templateId!),
                    'project_id': project["id"],
                    'assessment_content': element['assessment_content'],
                    'evaluation_criteria': element['evaluation_criteria'],
                    'weight_score': element['weight_score'],
                    'actual_details': element['actual_details'],
                    'actual_score': element['actual_score'],
                    'evaluation_opinions': evaluationOpinions
                  };
                  list.add(map);
                });
                PurchaseSupplierEvaluationOdooApi.batchSave(list)
                    .then((ResponseBodyApi res) {
                  if (!res.success!) {
                    CryUtils.message(res.message!);
                    return;
                  }
                  Navigator.pop(context, true);
                  EventBus.getPublisher().add({"type": "form:saved"});
                  CryUtils.message(S.of(context).saved);
                });
              }else{
                purchaselist.forEach((element) {
                  Map map = new HashMap();
                  map = {
                    'id': element['id'],
                    'actual_details': element['actual_details'],
                    'score': element['actual_score'],
                    'opinions': evaluationOpinions,
                  };
                  list.add(map);
                });
                PurchaseSupplierEvaluationOdooApi.batchUpdate(list)
                    .then((ResponseBodyApi res) {
                  if (!res.success!) {
                    CryUtils.message(res.message!);
                    return;
                  }
                  Navigator.pop(context, true);
                  EventBus.getPublisher().add({"type": "form:saved"});
                  CryUtils.message(S.of(context).saved);
                });
              }
            },
            iconData: Icons.save,
          ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        ),
      ],
    );
    var result = widget.isView?SingleChildScrollView(
      child: Column(
        children: [
          form,
        ],
      )):Scaffold(
      appBar: AppBar(
        title: Text('供应商评价打分'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            form,
          ],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
